<?php
namespace app\horoscope\controller;
use \app\check\controller\Check;
use \app\astro\controller\Data;
use \think\Db;

class Index extends Check
{
    // 十天干
    private $Heavenly_Stems = ["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"];
    // 十二地支
    private $Earthly_Branches = ["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"];

    private $Chinese_era = [];

    public function __construct()
    {
        parent::filter_xss();
        parent::__construct();// 接口调用验证
    }

    public function getHoroscope()
    {
        $this->Chinese_era = $this->getChineseEra();
        $userinfo = $this->getUserinfo();
        $sun_deg = $this->getSunDeg();
        $year = $userinfo['year'];
        if($sun_deg >= 300 && $sun_deg < 315) $year--;// 水瓶座 0-15°为前一年
        $year_stem_branche = $this->getYearStemBranche($year);
        $month_stem_branche = $this->getMonthStemBranche($this->Chinese_era[$year_stem_branche]);
        $day_stem_branche = $this->getDayStemBranche($userinfo);
        $hour_stem_branche = $this->getHourStemBranche($this->Chinese_era[$day_stem_branche],$userinfo);

        $str = '';
        $str .= $this->Chinese_era[$year_stem_branche];
        $str .= $month_stem_branche;
        $str .= $this->Chinese_era[$day_stem_branche];
        $str .= $hour_stem_branche;
        echo $str;
//        return ;

//        echo $str;

//        echo "<br/>";
//
//        $solar_lunar = $this->getSolarOrLunar($str);
//        // 阳男 || 阴女
//        // 阳年生的男命和阴年生的女命，从出生时间起往后数到下一个交节时间（用星盘求出距离出生太阳顺数最近的星座15度，太阳到该度的时间即是下一次交节时间），
//        // 换算成x天，可带小数点，以x/3，所得y即出生y年后交运（y可换算成a年b月c天后）
//        if(
//            ($solar_lunar === 0 && $userinfo['type'] == 1)
//            || ($solar_lunar === 1 && $userinfo['type'] == 2)
//        )
//        {
//            $next = (floor($sun_deg/15) + 1) * 15 ;
//            echo $next;
//
//            echo "<br/>";
//        }
//        // 阳女 || 阴男
//        // 阴年男命、阳年女命，从出生时间往前数，其它相同
//        else
//        {
//            $next = floor($sun_deg/15) * 15 ;
//            echo $next;
//
//            echo "<br/>";
//        }


    }

    /**
     * 阳年生 || 阴年生
     * @param string $str
     * @return int 0 阳 || 1阴
     */
    private function getSolarOrLunar($str = '')
    {
        $str = mb_substr($str,0,1,'utf-8');

        $num = array_search($str,$this->Heavenly_Stems);

        return $num % 2;
    }
    /**
     * 获取太阳度数
     * @return float
     */
    public function getSunDeg()
    {
        $Data = new Data();
        $userinfo = $this->getUserinfo();
        $timestamp1 =$Data->deal_time($userinfo);

        $utdatenow = strftime("%d.%m.%Y", $timestamp1);
        $utnow = strftime("%H:%M:%S", $timestamp1);

        $exec_str = config('astrolog.prefix')." -b{$utdatenow} -ut{$utnow} -p0 -fl -g, -head";

        exec ($exec_str, $out);

        if(is_array($out) && count($out) == 1)
            return floatval($out[0]);
        else
        {
            echo json_encode(['code'=>10086,'msg'=>'To get the sun deg error.']);
            exit;
        }
    }
    /**
     * 获取用户信息
     * @return mixed
     */
    private function getUserinfo()
    {
        $Data = new Data();
        $rid = Input::get('id','0');

        $userinfo = $Data->get_birth_data($rid);
        return $userinfo;
    }
    /**
     * 获取年干支
     * @param null $year
     * @return int
     */
    private function getYearStemBranche($year = null)
    {
        return ($year - 4) % 60 < 0 ? ($year - 4) % 60 + 60 : ($year - 4) % 60;
    }
    /**
     * 获取月干支
     * @param null $year_stem_branche
     * @return string
     */
    private function getMonthStemBranche($year_stem_branche = null)
    {
        // 每15度一个节气   总共二十四节气  月令地支
        $month_branche = ["卯","辰","辰","巳","巳","午","午","未","未","申","申","酉","酉","戌","戌","亥","亥","子","子","丑","丑","寅","寅","卯"];

        $temp =["寅","卯","辰","巳","午","未","申","酉","戌","亥","子","丑"];// 十二个月

//        $temp2 = ["丙","戊","庚","壬","甲","丙","戊","庚","壬","甲"];
        $temp2 = [2,4,6,8,0,2,4,6,8,0];

        $sun = $this->getSunDeg();

        $month_branche_str = $month_branche[floatval($sun/15)];// 月令地支

        $year_stem_branche = mb_substr($year_stem_branche,0,1,'utf-8');

        $year_num = array_search($year_stem_branche,$this->Heavenly_Stems);

        $start_num = $temp2[$year_num];

        $month_branche_num = array_search($month_branche_str,$temp);

        $newArr = array_merge($this->Heavenly_Stems,$this->Heavenly_Stems,$this->Heavenly_Stems);

        $s = [];
        for ($i=$start_num;$i<$start_num+12;$i++)
        {
            $s[] = $newArr[$i];
        }

        return $s[$month_branche_num].$month_branche_str;
    }
    /**
     * 获取日干支
     * @param array $userinfo
     * @param int $time2  strtotime('1999-11-8')
     * @return int
     */
    private function getDayStemBranche($userinfo = [],$time2 = 941990400)
    {
        $time1 = strtotime("{$userinfo['year']}-{$userinfo['month']}-{$userinfo['day']}");
        $val = ($time1 - $time2) / 3600 / 24 % 60;
        $val = $val < 0 ? $val + 60 : $val;
        return $val;
    }
    /**
     * 获取时辰干支
     * @param null $year_stem_branche
     * @return string
     */
    private function getHourStemBranche($day_stem_branche = null,$userinfo = [])
    {
        // 二十四小时，十二个时辰  时辰地支
        $hour_branche = ["子","丑","丑","寅","寅","卯","卯","辰","辰","巳","巳","午","午","未","未","申","申","酉","酉","戌","戌","亥","亥","子"];

//        $temp2 = ["甲","丙","戊","庚","壬","甲","丙","戊","庚","壬"];
        $temp2 = [0,2,4,6,8,0,2,4,6,8];

        $hour_branche_str = $hour_branche[$userinfo['hour']];// 时辰地支

        $day_stem_branche = mb_substr($day_stem_branche,0,1,'utf-8');

        $day_num = array_search($day_stem_branche,$this->Heavenly_Stems);

        $start_num = $temp2[$day_num];

        $hour_branche_num = array_search($hour_branche_str,$this->Earthly_Branches);

        $newArr = array_merge($this->Heavenly_Stems,$this->Heavenly_Stems,$this->Heavenly_Stems);

        $s = [];
        for ($i=$start_num;$i<$start_num+12;$i++)
        {
            $s[] = $newArr[$i];
        }

        return $s[$hour_branche_num].$hour_branche_str;
    }
    // 获取60甲子循环
    private function getChineseEra()
    {
        $Chinese_era = [];
        $k = 0;
        $n = 0;
        for($i = 0;$i < 6;$i++)
        {
            for($j = 0;$j < 10;$j++)
            {
                if($k == 12) $k = 0;

                $Chinese_era[$n] = $this->Heavenly_Stems[$j].$this->Earthly_Branches[$k];
                $n++;
                $k++;
            }
        }
        return $Chinese_era;
    }
}